<template>
  <px-drawer v-model="visible" @close="closeDrawer" @open="openDrawer">
    <template #header>
      <h3 style="font-weight: bold">设备{{ typeTitle }}</h3>
    </template>
    <template #default>
      <px-form ref="formRef" :model="formValue" :rules="rules" label-position="right" label-width="120px">
        <EquipFactorySelect />
        <EquipClassSelect :isRequired="true" :className="formValue.className" @changeClassName="changeClassName" />
        <px-form-item label="父级系统名称" prop="parentId">
          <px-tree-select
            v-model="formValue.parentId"
            :disabled="props.drawerType === 'addChild'"
            clearable
            filterable
            :default-expanded-keys="[0]"
            :props="{
              children: 'children',
              label: 'name',
              value: 'id'
            }"
            node-key="id"
            :data="systemList"
            check-strictly
            placeholder="请选择父级系统名称"
            style="width: 100%"
            @node-click="nodeClick"
            @visible-change="visibleChangeSystem"
            @clear="clearSystem"
          />
        </px-form-item>
        <px-form-item label="系统名称" prop="name">
          <px-input v-model="formValue.name" clearable placeholder="请输入系统名称" maxlength="50" />
        </px-form-item>
        <px-form-item label="排序" prop="sort">
          <px-input-number v-model="formValue.sort" placeholder="请输入排序" :min="0" maxlength="50" />
        </px-form-item>
      </px-form>
    </template>
    <template #footer>
      <px-button @click="closeDrawer">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </template>
  </px-drawer>
</template>
<script setup lang="ts">
import { computed, reactive, ref, toRefs } from "vue";
import { PxMessage } from "px-ui";
import EquipFactorySelect from "@/views/all/equip/components/EquipFactorySelect.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import { addEquipSystem, editEquipSystem } from "@/api/equip/archive";
import { querySystemTree } from "@/api/common";

// 调用父级-关闭抽屉、查询列表方法
const emits = defineEmits(["closeDrawer", "queryTable"]);

const formRef = ref();
const state = reactive<any>({
  formValue: {
    id: "",
    parentId: "",
    className: "",
    name: "",
    sort: ""
  },
  typeTitle: "系统新增",
  systemList: []
});
const { formValue, typeTitle, systemList } = toRefs(state);
const props = defineProps(["visible", "drawerType", "equipRow", "parentSystemName"]);
const visible = computed(() => props.visible);
// 表单校验规则
const rules = computed(() => ({
  name: [
    {
      required: true,
      message: "系统名称不能为空",
      trigger: ["blur", "change"]
    }
  ]
}));

// 打开抽屉
const openDrawer = async () => {
  formRef.value.resetFields();
  if (props.drawerType === "add") {
    // 系统新增，只添加顶级目录，没有id和parentId值
    typeTitle.value = "系统新增";
    formValue.value.className = "";
    formValue.value.name = "";
    formValue.value.sort = 0;
    delete formValue.value.id;
  } else if (props.drawerType === "edit") {
    typeTitle.value = "系统编辑";
    const { id, parentId, className, name, sort } = props.equipRow;
    formValue.value.id = id;
    formValue.value.parentId = parentId;
    formValue.value.className = className;
    formValue.value.name = name;
    formValue.value.sort = sort;
  } else if (props.drawerType === "addChildren") {
    typeTitle.value = "子系统新增";
    const { id, className } = props.equipRow;
    formValue.value.parentId = id;
    formValue.value.className = className;
    formValue.value.name = "";
    formValue.value.sort = "";
    delete formValue.value.id;
  }
  visibleChangeSystem(true);
};
// 关闭抽屉
const closeDrawer = () => {
  formRef.value.resetFields();
  emits("closeDrawer");
};
// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const params = formValue.value;
      if (props.drawerType === "add") {
        await addEquipSystem(params);
        PxMessage.success("新增成功");
        emits("closeDrawer");
        emits("queryTable");
      } else if (props.drawerType === "edit") {
        await editEquipSystem(params);
        PxMessage.success("编辑成功");
        emits("closeDrawer");
        emits("queryTable");
      } else if (props.drawerType === "addChildren") {
        await addEquipSystem(params);
        PxMessage.success("子系统新增成功");
        emits("closeDrawer");
        emits("queryTable");
      }
    }
  });
};
// 显示隐藏科室下拉列表
const visibleChangeSystem = async val => {
  if (val) {
    const tempSystemList = await querySystemTree({ className: formValue.value.className });
    const arr = tempSystemList || [];
    systemList.value = [{ name: "根节点", id: 0, children: arr }];
  } else {
    systemList.value = [{ name: "根节点", id: 0, children: [] }];
  }
};
// 点击左侧树节点，获取工厂、科室、系统、系统codes
const nodeClick = e1emData => {
  formValue.value.parentId = e1emData.parentId;
};
// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = val => {
  formValue.value.className = val;
  formRef.value?.resetFields(["parentId"]);
};
// 系统组件值改变触发
const clearSystem = () => {
  formRef.value?.resetFields(["parentId"]);
};
</script>
<style lang="scss" scoped>
:deep(.px-select) {
  width: 100%;
}

:deep(.px-input-number) {
  width: 100%;
}
</style>
